package com.example.easyexcel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.easyexcel.dao.AssetTargetInfoMapper;
import com.example.easyexcel.dto.AssetTargetInfo;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

@Slf4j
public class AssetTargetInfoSingleThreadListener extends AnalysisEventListener<AssetTargetInfo> {

    private final AssetTargetInfoMapper mapper;
    private static final int BATCH_SIZE = 10000;
    private final List<AssetTargetInfo> batchList = new ArrayList<>();

    // 移除了静态计数器，每个sheet独立统计
    private int totalProcessed = 0;
    private int totalInserted = 0;
    private int failedCount = 0;

    // 注意：assetNoCounter 改为实例变量，每个sheet独立计数
    private final AtomicLong assetNoCounter = new AtomicLong(0);

    public AssetTargetInfoSingleThreadListener(AssetTargetInfoMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public void invoke(AssetTargetInfo dto, AnalysisContext context) {
        try {
            AssetTargetInfo entity = convertToEntity(dto);
            batchList.add(entity);
            totalProcessed++;

            if (batchList.size() >= BATCH_SIZE) {
                saveBatchData();
            }
        } catch (Exception e) {
            failedCount++;
            log.error("Sheet[{}] 第{}行数据转换失败: {}",
                    context.readSheetHolder().getSheetName(),
                    context.readRowHolder().getRowIndex(),
                    e.getMessage());
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 处理最后一批数据
        if (!batchList.isEmpty()) {
            saveBatchData();
        }

        log.info("Sheet[{}] 导入完成: 成功 {} 条, 失败 {} 条, 总计 {} 条",
                context.readSheetHolder().getSheetName(),
                totalInserted, failedCount, totalProcessed);
    }

    private void saveBatchData() {
        if (batchList.isEmpty()) return;

        try {
            int inserted = mapper.insertBatch(batchList);
            totalInserted += inserted;
            log.debug("批量插入 {} 条数据, 成功 {} 条", batchList.size(), inserted);
        } catch (Exception e) {
            failedCount += batchList.size();
            log.error("批量插入失败: {}", e.getMessage());
        } finally {
            batchList.clear();
        }
    }

    private AssetTargetInfo convertToEntity(AssetTargetInfo dto) {
        AssetTargetInfo entity = new AssetTargetInfo();

        // 根据你的SQL字段进行映射
        entity.setTargetName(dto.getTargetName());
        entity.setTargetDefinition(dto.getTargetDefinition());
        entity.setTargetStatsCoverage(dto.getTargetStatsCoverage());
        entity.setTargetTc(convertTargetTc(dto.getTargetType()));

        // 生成asset_no - 每个sheet独立计数
        String assetNo = "MT" + String.format("%09d", assetNoCounter.getAndIncrement());
        entity.setAssetNo(assetNo);

        entity.setCntOrg(dto.getCntOrg());
        entity.setTimeDimensionTc(calculateTimeDimensionTc(dto));

        // 时间字段在SQL中由NOW()处理，这里设为null
        entity.setCreateTime(null);
        entity.setUpdateTime(null);
        entity.setDelFlag(dto.getDelFlag() != null ? dto.getDelFlag() : 0L);

        return entity;
    }

    private Integer convertTargetTc(String targetType) {
        if (targetType == null) return null;
        if (targetType.contains("基础指标")) return 0;
        if (targetType.contains("组合指标")) return 1;
        return null;
    }

    private Integer calculateTimeDimensionTc(AssetTargetInfo dto) {
        boolean hasCalendarYear = dto.getCalendarYear() != null &&
                !dto.getCalendarYear().trim().isEmpty();
        boolean hasLotteryYear = dto.getLotteryYear() != null &&
                !dto.getLotteryYear().trim().isEmpty();

        if (hasCalendarYear && hasLotteryYear) return 2;
        if (hasCalendarYear) return 0;
        if (hasLotteryYear) return 1;
        return null;
    }
}